﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using HtmlAgilityPack;
using System.Globalization;

namespace OlapProject
{
    class HomeOneSaleParser : BaseParser
    {
        private string SHORT_NAME = "hos";
        private Dictionary<string, string> typeToChange = new Dictionary<string, string>();

        public HomeOneSaleParser()
        {
            typeToChange["endofterrace"] ="house";
            typeToChange["terraced"] ="house";
            typeToChange["maisonette"] = "apartment ";
            typeToChange["landonly"] ="land";
            typeToChange["unusual"] = "other";
        }

        protected override string getNextPageLink(HtmlDocument document)
        {

            HtmlNode nextPageNode =
                document.DocumentNode.SelectSingleNode("//div[@class='pagination']/a[@class='prevnext'and text()='next »']");

            if (nextPageNode == null)
            {
                return base.getNextPageLink(document);
            }
            else
            {
                return "http://www.homesonsale.co.uk" + nextPageNode.GetAttributeValue("href", string.Empty);
            }
        }
        override protected void parsePage(HtmlAgilityPack.HtmlDocument document)
        {

            HtmlAgilityPack.HtmlDocument details = new HtmlAgilityPack.HtmlDocument();
            string detailsUrl = "";

            foreach (HtmlNode moreInfoNode in document.DocumentNode.SelectNodes("//strong[text()='More info']"))
            {
                detailsUrl = string.Empty;
                detailsUrl += moreInfoNode.ParentNode.GetAttributeValue("href", string.Empty);
                if (detailsUrl == string.Empty)
                    continue;

                detailsUrl = "http://www.homesonsale.co.uk/" + detailsUrl;

                if (loader.downloadHtmlDocument(detailsUrl, details))
                {
                    PropertyVO property = parsePropertyVO(details);
                    container.Add(property);
                }

            }    
  
        }

        private PropertyVO parsePropertyVO(HtmlDocument details)
        {      
            PropertyVO property = new PropertyVO();
            property.city = getValue(details, "City/Town: ");
            property.district = getValue(details, "Address of Property:");
            property.type =  changeTypeIfNeeded(getValue(details, "Type of Property:"));          
            property.bedrooms = getValueAsInt(details, "Bedrooms:");
            property.bathrooms = getValueAsInt(details, "Bathrooms: ");
   
            string price = Utlis.removeExtraText(getValue(details, "Price: "));
            try
            {
                property.price = Decimal.Parse(price, CultureInfo.InvariantCulture);
            }
            catch
            {
                property.price = 0;
            }

            parseCountry(details, property);
            property.source = SHORT_NAME;
            property.datetime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            return property;
        }

        private string changeTypeIfNeeded(string type)
        {
            type = type.Replace(" ", string.Empty);
            if (typeToChange.ContainsKey(type))
            {                
                return typeToChange[type];
            }
            return type == string.Empty ? "unspecified" : type;
        }

        private static void parseCountry(HtmlDocument details, PropertyVO property)
        {
            HtmlNode node = details.DocumentNode.SelectSingleNode("//strong[a[text()='Europe']]");
            HtmlNodeCollection collection = node.SelectNodes("a");
            if (collection.Count >= 2)
            {
                property.country = collection[1].InnerText.ToLower();
            }
        }

        private int getValueAsInt(HtmlDocument details, string key, int defaultValue = 0)
        {
            int value;
            string result = getValue(details, key);
            result = Utlis.removeExtraText(result);
            if(int.TryParse(result, out value))
                return value;
            return defaultValue;
        }

        private string getValue(HtmlDocument details, string key, string defaultValue = "")
        {
            string result = defaultValue;
            HtmlNode node = details.DocumentNode.SelectSingleNode("//tr[td/strong[text()='" + key + "']]");
            HtmlNodeCollection collection = node.SelectNodes("td");
            if (collection.Count >= 2)
            {
                result = collection[1].InnerText;
            }          
            return result.ToLower();
        }

        public override string pageUrl 
        {
            get
            {
                return "http://www.homesonsale.co.uk/europe-b6_0-en.html";                 
            } 
        }


        public override string parseName
        {
            get { return "Home on Sale"; }
        }

    }
}
